<template>
    <div class="app-container" style="padding: 0" ref="divDom">
        <vxe-grid ref="xGrid" v-bind="gridOptions" @checkbox-change="handleSelectionChange" :params="params" :height="tableHeight">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:dict:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:dict:remove']">删除</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_normal_disable" :value="row.status" />
            </template>
            <template #slotDictLabel="{ row }">
                <span v-if="row.listClass == '' || row.listClass == 'default'">{{ row.dictLabel }}</span>
                <el-tag v-else :type="row.listClass == 'primary' ? '' : row.listClass">{{ row.dictLabel }}</el-tag>
            </template>
            <template #action="{ row }">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:dict:edit']">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:dict:remove']">删除</el-button>
            </template>
        </vxe-grid>
        <dictDataItemEdit :dialog-visible="dialog.isVisible" :dictData="dictData" :type="dialog.type" @close="editClose" @success="editSuccess" ref="edit" />
    </div>
</template>
<script setup lang="ts" name="DictDataItemManage">
    import dictDataItemEdit from "./dictDataItemEdit";
    import { reactive, getCurrentInstance, ref, toRefs, watch, onMounted, onBeforeUnmount, Ref } from "vue";
    import useDictStore from "@/store/modules/dict";
    import { pageData, getData, delData } from "@/api/system/dict/data";
    import { VxeGridInstance, VxeGridProps } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import { isEmpty } from "@/utils/is";
    import { getViewportOffset } from "@/utils/domUtils";
    const edit = ref<InstanceType<typeof dictDataItemEdit>>();
    const props = defineProps({
        dictTypeRecord: {
            type: Object,
            default: () => {
                reateBy: null;
                createTime: null;
                dictDescribe: null;
                dictId: -1;
                dictName: null;
                dictType: null;
                remark: null;
                status: null;
                tempMenuId: null;
                tempRoleId: null;
                updateBy: null;
                updateTime: null;
            },
        },
    });
    const { proxy } = getCurrentInstance() as any;
    const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
    const open = ref(false);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const title = ref("");
    const defaultDictType = ref("-1");
    const xGrid = ref({} as VxeGridInstance);
    const dictData = ref<Object>({});
    //额外请求参数
    const params = ref({});
    // 数据标签回显样式
    const listClassOptions = ref([
        { value: "default", label: "默认" },
        { value: "primary", label: "主要" },
        { value: "success", label: "成功" },
        { value: "info", label: "信息" },
        { value: "warning", label: "警告" },
        { value: "danger", label: "危险" },
    ]);
    const data: any = reactive({
        rules: {
            dictLabel: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
            dictValue: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
            dictSort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }],
        },
    });

    const { queryParams, rules } = toRefs(data);
    //弹窗
    const dialog = ref({
        isVisible: false,
        type: "add",
    });

    const divDom = ref() as Ref<HTMLDivElement>;
    const tableHeight = ref("100%");
    function calcHeight() {
        const viewport = getViewportOffset(divDom.value);
        tableHeight.value = viewport.bottomIncludeBody - 30;
    }
    onMounted(() => {
        const viewport = getViewportOffset(divDom.value);
        tableHeight.value = viewport.bottomIncludeBody - 30;
    });
    onMounted(() => {
        calcHeight();
        window.addEventListener("resize", calcHeight);
    });
    onBeforeUnmount(() => {
        window.removeEventListener("resize", calcHeight);
    });
    // 表格配置
    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "dictCode",
        height: tableHeight.value,
        rowId: "dictCode",
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 100,
            titleAlign: "right",
            items: [
                {
                    field: "dictLabel",
                    title: "字典标签",
                    span: 8,
                    itemRender: { name: "$input", props: { placeholder: "请输入字典标签" } },
                },
                {
                    field: "status",
                    title: "状态",
                    span: 8,
                    itemRender: {
                        name: "$select",
                        options: sys_normal_disable,
                    },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
            export: proxy.$auth.hasPermi("system:dict:export"),
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        proxyConfig: {
            paramsChangeLoad: true, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }) => {
                    const queryParams: any = Object.assign({}, form);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }) => {
                        queryParams[property] = values.join(",");
                    });
                    return pageData({
                        ...page,
                        ...queryParams,
                        ...params,
                        dictType: props.dictTypeRecord?.dictType,
                    }).then((response) => {
                        return response;
                    });
                },
            },
        },
        checkboxConfig: {
            trigger: "row",
        },
        columns: [
            { type: "checkbox", width: 60 },
            {
                field: "dictCode",
                title: "字典编码",
                sortable: true,
            },
            {
                field: "dictLabel",
                title: "字典标签",
                slots: {
                    default: "slotDictLabel",
                },
            },
            {
                field: "dictValue",
                title: "字典键值",
                sortable: true,
            },
            {
                field: "dictSort",
                title: "字典排序",
                sortable: true,
            },
            {
                field: "status",
                title: "状态",
                filters: sys_normal_disable,
                slots: {
                    default: "slotStatus",
                },
            },
            {
                field: "remark",
                title: "备注",
                sortable: true,
            },
            {
                field: "createTime",
                title: "创建时间",
                visible: false,
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },

            {
                title: "操作",
                width: 150,
                align: "center",
                fixed: "right",
                slots: { default: "action" },
            },
        ],
    });

    watch(
        () => props.dictTypeRecord,
        () => {
            params.value = {
                dictType: props.dictTypeRecord?.dictType,
            };
        },
        {
            deep: true,
        }
    );

    /** 新增按钮操作 */
    function handleAdd() {
        if (isEmpty(props.dictTypeRecord)) {
            proxy.$modal.msgError("请选择一个字典类型");
            return;
        }
        dictData.value["dictType"] = props.dictTypeRecord?.dictType;
        dialog.value.isVisible = true;
        dialog.value.type = "add";
    }
    /** 多选框选中数据 */
    function handleSelectionChange(selection: any) {
        ids.value = selection.records.map((item: any) => item.dictCode);
        single.value = selection.records.length != 1;
        multiple.value = !selection.records.length;
    }
    /** 修改按钮操作 */
    function handleUpdate(row: any) {
        const dictCode = row.dictCode || ids.value;
        getData(dictCode).then((response) => {
            dictData.value = response.data;
            dialog.value.isVisible = true;
            dialog.value.type = "edit";
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row: any) {
        const dictCodes = row.dictCode || ids.value;
        proxy.$modal
            .confirm('是否确认删除字典编码为"' + dictCodes + '"的数据项？')
            .then(function () {
                return delData(dictCodes);
            })
            .then(() => {
                xGrid.value.commitProxy("reload");
                proxy.$modal.msgSuccess("删除成功");
                useDictStore().removeDict(queryParams.value.dictType);
            })
            .catch(() => {});
    }
    /**弹窗操作 */
    function editClose() {
        dialog.value.isVisible = false;
    }
    function editSuccess() {
        dialog.value.isVisible = false;
    }
</script>
<style lang="scss" scoped></style>
